<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div ref="ele">
        <!-- 搜索 -->
        <label class="el-form-item-label">运单号</label>
        <el-input v-model="query.transportTakeNo" placeholder="订单号" clearable style="width: 155px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--<label class="el-form-item-label">煤矿名称</label>
        <el-select v-model="query.mineMouthId" filterable placeholder="全部" clearable @change="crud.toQuery" style="width: 155px;" class="filter-item">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.mineMouthName"
            :value="item.id">
          </el-option>
        </el-select>-->
        <label class="el-form-item-label">结算人电话</label>
        <el-input v-model="query.applyUserPhone" clearable placeholder="结算人电话" style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">结算单号</label>
        <el-input v-model="query.settlementNo" placeholder="结算号" clearable style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">申请时间</label>
        <date-range-picker v-model="query.createTime" class="date-item" />
        <label class="el-form-item-label" v-if="this.activeName === '3'">结算时间</label>
        <date-range-picker v-model="query.createTime" class="date-item" v-if="this.activeName === '3'"/>
        <rrOperation :crud="crud" />
      </div>
      <!--<crudOperation :permission="permission"></crudOperation>-->
    </div>
    <el-tabs v-model="activeName" style="padding: 0" type="card"  @tab-click="handleClick">
      <el-tab-pane label="全部" name="null"></el-tab-pane>
      <el-tab-pane label="待结算" name="1"></el-tab-pane>
      <el-tab-pane label="已结算" name="3"></el-tab-pane>
      <el-tab-pane label="退回" name="2"></el-tab-pane>

    <!--表格渲染-->
    <el-table
      :height="tableHeight"
      ref="table"
      border
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
      :summary-method="getCommSummaries({customer: crud.totalObject, titleIndex: 0})" :show-summary="false" >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column prop="settlementNo" width="175"  label="结算单号" align="center" show-overflow-tooltip />
      <el-table-column prop="applyUserName" width="100"  label="申请人姓名" align="center" show-overflow-tooltip />
      <el-table-column prop="applyUserPhone" width="100"  label="申请人电话" align="center" show-overflow-tooltip />
      <el-table-column prop="settlementAmount" width="100"  label="结算总金额" align="center" show-overflow-tooltip >
        <template slot-scope="scope">
          <span class="search-text1">{{scope.row.settlementAmount | nullFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="mineSendNum" width="100"  label="矿发吨位" align="center" show-overflow-tooltip />
      <el-table-column prop="realNum" width="100"  label="实收吨位" align="center" show-overflow-tooltip />
      <el-table-column prop="diffNum" width="100"  label="差异吨位" align="center" show-overflow-tooltip />
      <el-table-column prop="freight" width="100"  label="运费" align="center" show-overflow-tooltip />
      <el-table-column prop="loadFee" width="100"  label="装车费" align="center" show-overflow-tooltip />
      <el-table-column prop="unloadFee" width="100"  label="卸车费" align="center" show-overflow-tooltip />
      <el-table-column prop="poundsFee" width="100"  label="磅费" align="center" show-overflow-tooltip />
      <el-table-column prop="otherFee" width="100"  label="其他费用" align="center" show-overflow-tooltip />
      <el-table-column prop="remark" width="100"  label="备注" align="center" show-overflow-tooltip />
      <el-table-column prop="status" align="center" width="90" show-overflow-tooltip label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
            {{ scope.row.status === 1 ? "待结算" : scope.row.status === 2 ? "退回" : "已结算" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="casue" v-if="activeName === 'null' || activeName === '2'" width="100"  label="退回原因" align="center" show-overflow-tooltip />
      <el-table-column prop="applyDate" width="150"  label="申请时间" align="center" show-overflow-tooltip >
        <template slot-scope="scope">
          {{parseTime(scope.row.applyDate,'{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>
      <el-table-column prop="cleanDate" width="150"  label="结算时间" v-if="activeName === 'null' || activeName === '3'" align="center" show-overflow-tooltip >
        <template slot-scope="scope">
          {{parseTime(scope.row.cleanDate,'{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>
      <el-table-column prop="transportTakeNo" width="170"  label="订单号" align="center" show-overflow-tooltip />
      <el-table-column prop="merchantName" width="120" align="center" label="运输公司" show-overflow-tooltip />
      <el-table-column label="操作" width="200"  align="center" fixed="right" v-if="activeName === '1' || activeName === 'null'">
        <template slot-scope="scope">
          <el-button size="mini"
                     v-if="scope.row.status === 1"
                     type="primary"
                     v-permission="['platformFreightSettle:settle']"
                     @click="createBtnClick(scope.row)">确认结算</el-button>
          <el-button size="mini" type="danger"
                     v-if="scope.row.status === 1"
                     v-permission="['platformFreightSettle:reject']"
                     @click="refuseBtnClick(scope.row)">驳回</el-button>
        </template>
      </el-table-column>
      <!--<el-table-column label="订单流程" align="center" width="95" fixed="right" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top" width="500">
            <el-table :data="scope.row.merchantOrderRecords">
              <el-table-column width="100" property="username" label="操作人账号"></el-table-column>
              <el-table-column width="90" property="orderStatus" label="操作状态">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.orderStatus === 1 ? 'success' : 'warning'">
                    {{ scope.row.orderStatus | orderStatusFilter }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column width="120" property="operationTime" show-overflow-tooltip label="操作时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.operationTime)}}</span>
                </template>
              </el-table-column>
              <el-table-column property="remark" show-overflow-tooltip label="操作备注"></el-table-column>
            </el-table>
            <a slot="reference" class="name-wrapper">
              <el-tag size="medium">操作流程</el-tag>
            </a>
          </el-popover>
        </template>
      </el-table-column>-->
    </el-table>
    <!--分页组件-->
    <pagination />
    </el-tabs>
    <div class="panel">
      <form-panel v-if="showFormPanel" :showFormPanel.sync="showFormPanel" :item="selectedItem" v-on:refreshList="crud.toQuery"></form-panel>
    </div>
    <el-dialog
      title="驳回原因"
      class="tiny-mce-dialog"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form ref="causeValue" :model="causeValue" :rules="causeValues" size="small" label-width="80px">
        <el-card class="box-card">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="原因" prop="casue" label-width="80px">
                <el-input
                  clearable
                  type="textarea"
                  placeholder="请输入驳回原因"
                  v-model="causeValue.casue"
                  :autosize="{ minRows: 6, maxRows: 10}"
                  maxlength="200"
                  show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-loading="fullscreenLoading" type="success" @click="save(false)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, {crud, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Form from './form'

export default {
  name: 'PlatformFreightSettle',
  components: { pagination, rrOperation, DateRangePicker, 'form-panel': Form },
  mixins: [presenter(), header(), crud()],
  cruds() {
    return CRUD({ title: '运输公司结算司机运费', url: 'api/platformFreightSettle/list', query: { status: 1 }, idField: 'allotTime', sort: 'allotTime,desc', crudMethod: { }})
  },
  data() {
    return {
      activeName: '1',
      showFormPanel: false,
      dialogVisible: false,
      fullscreenLoading: false,
      causeValue: {},
      freightSettlementId: null,
      height: this.getTableHeight({}),
      tableHeight: this.height,
      echodisplaylist: [],
      selectedItem: {},
      dialogFormVisible: false,
      options: [],
      merchant: [],
      coalType: [
        { name: '全部', ecode: null, id: null }
      ],
      coalName: [],
      coalData: null,
      coalValueData: {},
      status: [
        {key: '全部',value: null},
        {key: '已下单',value: 1},
        {key: '用户取消',value: 2},
        {key: '商户确认',value: 3},
        {key: '商户拒绝',value: 4},
        {key: '关闭（24小时）',value: 5},
        {key: '已支付',value: 6},
        {key: '商户确认',value: 7}
      ],
      priceUnit: '',
      baseCatesValue: [],
      forms: {
        coalInfos: []
      },
      causeValues: {
        casue: [
          { required: true, message: '请输入驳回原因', trigger: 'blur' }
        ]
      },
      permission: {
        add: ['admin', 'coalProducts:add'],
        edit: ['admin', 'coalProducts:edit'],
        del: ['admin', 'coalProducts:del']
      }
    }
  },

  created() {
    this.crud.optShow = {
      reset: true,
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  methods: {
    createBtnClick (value) {
      this.selectedItem = value
      this.showFormPanel = true
    },
    handleClick() {
      let self = this
      self.crud.query.status = self.activeName === 'null' ? null : self.activeName
      self.crud.toQuery()
    },
    save (val) {
      let self = this
      let pram = {
        id: self.freightSettlementId,
        msg: self.causeValue.casue,
        falg: val
      }
      self.$refs['causeValue'].validate((valid) => {
        if (valid) {
          self.fullscreenLoading = true
          self.$http.post('/api/platformFreightSettle/reject', pram)
            .then(function (res) {
              self.fullscreenLoading = false
              self.dialogVisible = false
              self.crud.toQuery()
            }).catch(function (error) {
            self.fullscreenLoading = false
            console.log(error)
          })
        }
      })
    },
    /*createBtnClick(value) {
      let self = this
      self.$confirm('确定要确认该订单吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let pram = {
          id: value.freightSettlementId,
          falg: true
        }
        self.$http.put('/api/supplyOrder/operation', pram)
          .then(function (res) {
            self.fullscreenLoading = false
            self.dialogVisible = false
            if (res.ok){
              self.$message({
                type: 'success',
                message: '确认成功!'
              })
              self.crud.toQuery()
            }
          }).catch(function (error) {
            self.fullscreenLoading = false
            console.log(error)
        })
      }).catch(() => {
        /!*this.$message({
          type: 'info',
          message: '已取消确认'
        });*!/
      })
    },*/
    refuseBtnClick (value) {
      this.freightSettlementId = value.freightSettlementId
      this.dialogVisible = true
    },
    getCurrentMonthFirst () {
      var date = new Date()
      date.setDate(1)
      date.setHours(0)
      date.setSeconds(0)
      date.setMinutes(0)
      return date
    },
    getCommSummaries({column, customer, title = '合计', titleIndex}) {
      this.$nextTick(() => {
        this.$refs['table'].doLayout();
      })
      return function (param) {
        const sums = []
        const {columns, data} = param
        columns.forEach((columnItem, index) => {
          if ((titleIndex === undefined && columnItem.type === 'index') || index === titleIndex) {
            sums[index] = title
          } else if (customer) {
            sums[index] = customer[columnItem.property] === null || customer[columnItem.property] === undefined || customer[columnItem.property] === '' ? '-' : customer[columnItem.property]
          } else {
            let sumList = []
            column.forEach((e) => {
              if (e.toString().includes('-')) {
                for (let i = Number(e.split('-')[0]); i <= Number(e.split('-')[1]); i++) {
                  sumList.push(i)
                }
              } else {
                sumList.push(Number(e))
              }
            })
            if (sumList.includes(index)) {
              const values = data.map(e => Number(e[columnItem.property]))
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += ''
              } else {
                sums[index] = '-'
              }
            }
          }
        })
        return sums
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    objectKey(key,value){
      let keyValue={};
      keyValue[key]=value;
      return key;
    },
    search(){
      let self = this
      self.$http.get("/api/mineMouth/getMineMouth").then(function(value) {
        self.options = value
      })
      self.$http.get("/api/systemController/getMerchant").then(function(value) {
        if (value.ok){
          self.merchant = value.data
        }
      })
    },
    getCategory(){
      let self = this
      self.$http.get("/api/coalCategory/query").then(function(value) {
        self.coalType = self.coalType.concat(value)
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  },
  mounted: function () {
    this.tableHeight =  this.height - this.$refs.ele.clientHeight - 10
    this.getCategory()
    this.search()
  },
}
</script>

<style scoped>

</style>
